#!/usr/bin/env bash
#
# This is the guided installer for the SolveBio Ruby Client:
#
#    curl -kL install.solve.bio/ruby | bash
#

echo
echo "     ____        _           ____  _"
echo "    / ___|  ___ | |_   _____| __ )(_) ___"
echo "    \___ \ / _ \| \ \ / / _ \  _ \| |/ _ \\"
echo "     ___) | (_) | |\ V /  __/ |_) | | (_) |"
echo "    |____/ \___/|_| \_/ \___|____/|_|\___/"
echo
echo "    Copyright © 2014 Solve, Inc. <https://www.solvebio.com>. All rights reserved."
echo

shopt -s extglob

function fail_exit() {
    echo
    echo "    #####################################"
    echo
    echo "    Failed to install SolveBio."
    echo "    Contact us at support@solvebio.com for help."
    echo
    echo "    In your email, please copy/paste the output of:"
    echo "        cat ${LOG}"
    echo
    echo "    #####################################"
    echo
    exit
}

trap ctrl_c INT

function ctrl_c() {
    echo
    echo
    echo "    Installation was aborted..."
    fail_exit
}

echo "    Installing SolveBio for Ruby..."
echo

# Setup the log
LOG=/tmp/solvebio-ruby.log
echo "SolveBio Ruby Guided Installer log" > $LOG
echo `date` >> $LOG

RUBY=`which ruby`

if [ "$RUBY" == "" ]; then
    echo "    Ruby is not installed. Please install Ruby before installing SolveBio for Ruby."
    fail_exit
fi

GEM=`which gem`

if [ "$RUBY" == "" ]; then
    echo "    Ruby is not installed. Please install Ruby before installing SolveBio for Ruby."
    fail_exit
fi

# TODO: check ruby and gem versions
GEM_OWNER=`ls -l $GEM | awk '{ print $3 }'`

if [ "$GEM_OWNER" == "root" ]; then
    GEM_SUDO="sudo ${GEM}"
    echo "    IMPORTANT: Your computer's password may be required. It will NOT be sent to SolveBio."
else
    GEM_SUDO=$GEM
fi

$GEM_SUDO install solvebio 2>&1 >> $LOG

if [ $? -eq 0 ]; then
    VERSION=`ruby -e "require 'solvebio'; print SolveBio::VERSION"`
    echo
    echo "    ##############################################"
    echo
    echo "    Success! SolveBio for Ruby ${VERSION} is now installed."
    echo
    echo "    Please run 'solvebio.rb login' to finish the setup."
    echo
    echo "    ##############################################"
    echo

    # Detect old credentials in ~/.netrc (they will interfere with Ruby's Rest Client)
    NETRC_WARN=`grep -c "solvebio" ~/.netrc`
    if [ "$NETRC_WARN" -gt "0" ]; then
        echo
        echo "Warning: SolveBio credentials were found in ~/.netrc"
        echo "Please delete the lines in ~/.netrc with SolveBio credentials."
        echo
    fi
else
    fail_exit
fi
